Voorbeeld van de instructie Function

Dit voorbeeld maakt gebruik van de instructie Function om de naam, argumenten en programmacode die het hoofddeel van de procedure Function vormen, te declareren. Het laatste voorbeeld maakt gebruik van harde, geāˆ©nitialiseerde Optional-argumenten.

' The following user-defined function returns the square root of the
' argument passed to it.
Function CalculateSquareRoot(NumberArg As Double) As Double
    If NumberArg < 0 Then    ' Evaluate argument.
        Exit Function    ' Exit to calling procedure.
    Else
        CalculateSquareRoot = Sqr(NumberArg)    ' Return square root.
    End If
End Function

Met behulp van het sleutelwoord ParamArray kan een functie een variabel aantal argumenten accepteren. In de volgende definitie wordt FirstArg als een waarde doorgegeven.

Function CalcSum(ByVal FirstArg As Integer, ParamArray OtherArgs())
Dim ReturnValue
' If the function is invoked as follows:
ReturnValue = CalcSum(4, 3 ,2 ,1)
' Local variables are assigned the following values: FirstArg = 4,
' OtherArgs(1) = 3, OtherArgs(2) = 2, and so on, assuming default
' lower bound for arrays = 1.

Optional-argumenten kunnen andere standaardwaarden en -typen hebben dan Variant.

' If a function's arguments are defined as follows:
Function MyFunc(MyStr As String, Optional MyArg1 As _ Integer = 5, Optional MyArg2 = "Desiree") 
Dim RetVal
' The function can be invoked as follows:
RetVal = MyFunc("Hallo", 2, "wereld")    ' All 3 arguments supplied.
RetVal = MyFunc("Test", , 5)    ' Second argument omitted.
' Arguments one and three using named-arguments.
RetVal = MyFunc(MyStr:="Hallo ", MyArg1:=7)